package com.mingsoft.led.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Utils {

	public static void sleep(long t) {
		try {
			Thread.sleep(t);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static String toUTF8String(String s) {
		// try {
		// return new String(s.getBytes(), "UTF-8");
		// } catch (UnsupportedEncodingException e) {
		// e.printStackTrace();
		// }
		return s;
	}

	public static byte[] getImgThumbs(File f, int w, int h, String name) {
		System.out.println("Check file for thumbs:" + f.getAbsolutePath());
		System.out.println(f.getAbsolutePath() + "is a file?" + f.isFile());
		System.out.println(f.getAbsolutePath() + "can be read?" + f.canRead());
		System.out.println(f.getAbsolutePath() + "is an image?"
				+ f.getName().toLowerCase().endsWith(".jpg"));

		if (f.isFile() && f.canRead()
				&& f.getName().toLowerCase().endsWith(".jpg")) {
			BufferedImage img = null;
			BufferedImage imgTo = null;
			ByteArrayOutputStream bos = null;
			try {
				img = ImageIO.read(f);
				imgTo = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
				Graphics2D g = (Graphics2D) imgTo.getGraphics();
				g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
						RenderingHints.VALUE_INTERPOLATION_BILINEAR);
				g.drawImage(img, 0, 0, w, h, 0, 0, img.getWidth(),
						img.getHeight(), null);
				g.setColor(new Color(200, 200, 200, 80));
				g.fillRect(0, 0, w, h);

				g.setFont(new Font(g.getFont().getName(), Font.BOLD, 24));

				g.setColor(new Color(0, 0, 0));
				g.drawString(name, 2, g.getFont().getSize() + 2);

				bos = new ByteArrayOutputStream();
				ImageIO.write(imgTo, "JPG", bos);
				return bos.toByteArray();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (bos != null) {
					try {
						bos.close();
					} catch (IOException e) {
					}
					bos = null;
				}
				if (img != null) {
					img.flush();
					img = null;
				}
			}
		}

		return null;
	}
}
